package com.micro.core.configuration;

import com.micro.plugins.mapper.wrapper.CamelCaseWapperFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Classname MybatisConfiguration
 * @Description mybatis配置类
 * @Author 汽车下的路灯
 * @Date 2019-11-27 上午 10:16
 * @Version 1.0.0
 */
@Slf4j
@Configuration
public class MybatisConfiguration {

    /** 数据库操作工厂 */
    public static final String SQL_SESSION_FACTORY = "sqlSessionFactory";

    /** 配置类型别名 */
    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;

    /**  配置mapper的扫描，找到所有的mapper.xml映射文件 */
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    /** 加载全局的配置文件 */
    @Value("${mybatis.config-location}")
    private String configLocation;

    @Autowired
    private DataSource dataSource;

    @Bean(name = SQL_SESSION_FACTORY)
    public SqlSessionFactory sqlSessionFactoryBean() {
        try {
            SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
            sessionFactoryBean.setDataSource(dataSource);
            sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperLocations);
            sessionFactoryBean.setMapperLocations(resources);
            //重写mybatis驼峰转换
            sessionFactoryBean.setObjectWrapperFactory(new CamelCaseWapperFactory());
            sessionFactoryBean.setConfigLocation( new DefaultResourceLoader().getResource(configLocation));
            return sessionFactoryBean.getObject();
        } catch (IOException e) {
            log.error("mybatis resolver mapper *xml is error >> e:{}",e);
            return null;
        } catch (Exception e) {
            log.error("mybatis sqlSessionFactoryBean create error >> e:{}",e);
            return null;
        }
    }

}
